/*
 * Copyright (c) 2001, 2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.core.internal.api;

import java.util.Date;
import java.util.Map;

import net.sourceforge.perforce.core.resources.IChangelist;

/** Internal helper class.
  * 
  * @version $Revision: 45 $
  * @author  <a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
final class Helper
{
	// ------------------------------------------------------------------------ Private Constructors
	
	/** Constructor for Helper. Utility classes won't be instantiated. */
	private Helper()
	{
	}

	// ----------------------------------------------------------------------- Public Static Methods

	/** Helper method returning either the associated string value or an empty
	  * string.
	  * 
	  * @param map the map.
	  * @param key the key.
	  * @return the value.
	  */
	public static final String safeGetString(Map map, String key)
	{
		String value = (String) map.get(key);
		return (value != null) ? value : "";                                           //$NON-NLS-1$
	}

	/** Helper method either returning the associated date value or the current
	  * time.
	  * 
	  * @param map the map.
	  * @param key the key.
	  * @return the value.
	  */
	public static final Date safeGetDate(Map map, String key)
	{
		String value = safeGetString(map, key);
		return !value.equals("") ? decodeTime(value) : new Date();                     //$NON-NLS-1$
	}
	
	/** Helper method either returning the associated integer or 0.
	  * 
	  * @param map the map.
	  * @param key the key.
	  * @return the value.
	  */
	public static final Integer safeGetInteger(Map map, String key)
	{
		String value = safeGetString(map, key);
		return !value.equals("") ? Integer.valueOf(value) : new Integer(0); //$NON-NLS-1$
	}

	/** Helper method either returning the associated changelist number of -1 for default.
	  *
	  * @param map the map.
	  * @param key the key.
	  * @return the value. 
	  */
	public static final Integer safeGetChangelist(Map map, String key)
	{
		String value = safeGetString(map, key);
		return 
			!value.equals("default") ?                                                 //$NON-NLS-1$
			Integer.valueOf(value) : 
			IChangelist.DEFAULT;
	}
	
	/** Helper method for decoding the Perforce time format to a java.util.Date
	  * object.
	  * 
	  * @param timeString the perforce time string.
	  * @return the decoded date.
	  */
	public static final Date decodeTime(String timeString)
	{
		long timeInt = Integer.parseInt(timeString);
		return new Date(timeInt * 1000);		
	}	
}
